<template>
  <el-table ref="table" :data="rows" border @selection-change="handleSelectionChange">
    <el-table-column v-if="selector !== false" type="selection" v-bind="selector" width="55" />
    <template v-if="columns">
      <el-table-column
        v-for="column in columns"
        v-bind="column"
        :key="column.name"
        :prop="column.name"
      >
        <template #default="{ row }">
          <column-cell :row="row" v-bind="column" />
        </template>
      </el-table-column>
    </template>
    <slot></slot>
  </el-table>
</template>

<script lang="ts" setup>
  import { ElTable, ElTableColumn } from 'element-plus';
  import { Column } from './table';
  import { Row } from '../elementui';
  import ColumnCell from './cell/ColumnCell.vue';
  import { ref, watchEffect } from 'vue';

  const props = defineProps<{
    columns?: Array<Column>;
    selector?: boolean;
    rows?: Array<Row>;
    selected?: Array<number | string | undefined>;
  }>();

  const emit = defineEmits(['command', 'update:selected']);

  const table = ref<InstanceType<typeof ElTable>>();

  const toggleSelection = (ids?: Array<number | string | undefined>) => {
    if (!table.value) return;
    if (ids) {
      props.rows?.forEach((row) => {
        table.value?.toggleRowSelection(row, !!row.id && -1 !== ids.findIndex((i) => i === row.id));
      });
    } else {
      table.value.clearSelection();
    }
  };

  const handleSelectionChange = (val: Row[]) => {
    emit(
      'update:selected',
      val.map((r) => r.id)
    );
  };

  watchEffect(() => toggleSelection(props.selected));
</script>

<style scoped></style>
